//
//  CXBFileSystemController.m
//  CocoaXBI
//

#import "CXBFileSystemController.h"

#import "CXBFileSystemElement.h"

@implementation CXBFileSystemController

#pragma mark Drag'n'drop setup

- (void)awakeFromNib {    
    [_fileSystemView setDataSource:self];
    
    [_fileSystemView registerForDraggedTypes:[NSArray arrayWithObjects:NSFilesPromisePboardType, nil]];
    
    [ _fileSystemView setDraggingSourceOperationMask:NSDragOperationNone forLocal:YES];
    // Support inter-application drag'n'drop
    [ _fileSystemView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:NO];
}

- (BOOL)outlineView:(NSOutlineView *)view writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard {
    NSAssert([items count] <= 1, @"Multiple selection not supported");
    [pboard declareTypes:[NSArray arrayWithObject:NSFilesPromisePboardType] owner:self];
    NSMutableArray * fileTypes = [[NSMutableArray alloc] init];
    for (id currentTreeElement in items) {
        NSAssert([[currentTreeElement representedObject] isKindOfClass:[CXBFileSystemElement class]], @"Wrong tree controller");
        CXBFileSystemElement * currentFSElement = (CXBFileSystemElement *)[currentTreeElement representedObject];
        [fileTypes addObject:[currentFSElement.name pathExtension]];
    }
    [pboard setPropertyList:fileTypes forType:NSFilesPromisePboardType];
    [fileTypes release];
    return YES;
}

- (NSArray *)outlineView:(NSOutlineView *)outlineView namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination forDraggedItems:(NSArray *)items {
    NSAssert([items count] <= 1, @"Multiple selection not supported");
    for (id currentTreeElement in items) {
        NSAssert([[currentTreeElement representedObject] isKindOfClass:[CXBFileSystemElement class]], @"Wrong tree controller");
        CXBFileSystemElement * currentFSElement = (CXBFileSystemElement *)[currentTreeElement representedObject];
        [currentFSElement writeToFileAtURL:dropDestination];
    }
    return [NSArray arrayWithObject:@"test.txt"];
}

- (NSDragOperation)outlineView:(NSOutlineView *)view validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(int)index {
    // Never accept drop TO the outline view
    return NSDragOperationNone;
}


@end
